import { Panel } from 'comps/common';
import { Table, Button, Form, Input, Modal, Icon, Popconfirm } from 'antd';
import _ from 'lodash';
import * as React from 'react';

const FormItem = Form.Item;

const mapPropsToFields = ({ source = {} }) => _.mapValues(source, v => {
  return { value: v };
});

class MachineSourceForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = { submiting: false };
  }

  doSubmit(evt) {
    const { form: { getFieldsValue }, onSubmit } = this.props;
    evt.preventDefault();
    this.setState({ submiting: true });
    return onSubmit(getFieldsValue())
      .then(() => this.setState({ submiting: false }));
  }

  render() {
    const { getFieldProps } = this.props.form;

    return (
      <Form horizontal onSubmit={::this.doSubmit}>
        <Input type='hidden' {...getFieldProps('id')}/>
        <FormItem label='名称' required>
          <Input type='text' {...getFieldProps('name')}/>
        </FormItem>
        <FormItem label='Master Url'>
          <Input type='text' addonBefore='http://' {...getFieldProps('masterUrls')}/>
        </FormItem>
        <Button htmlType='submit' type='primary' loading={this.state.submiting}>提交</Button>
      </Form>
    );
  }
}
MachineSourceForm = Form.create({ mapPropsToFields })(MachineSourceForm);

class EditMachineSourceModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
      source: {}
    };
  }

  onSubmit(newMachineData) {
    const handler = this.state.source.id ? this.props.onMachineSourceUpdate : this.props.onMachineSourceInsert;
    return handler(newMachineData, this.props.companyId)
      .then(() => {
        this.close();
      });
  }

  close() {
    this.refs.form.resetFields();
    this.setState({ show: false, source: {} });
  }

  show(source = {}) {
    this.setState({ show: true, source });
  }

  render() {
    return (
      <Modal title='机器来源'
        visible={this.state.show}
        footer={undefined}
        onCancel={::this.close}
      >
        <MachineSourceForm ref='form' source={this.state.source} onSubmit={::this.onSubmit}/>
      </Modal>
    );
  }
}

class MachineSourceManage extends React.Component {

  lockSource(source) {
    return ()=> {
      this.props.onLockSource(source)
    }
  }

  unlockSource(source) {
    return ()=> {
      this.props.onUnlockSource(source)
    }
  }

  render() {
    const { isFetching, sources = [], companyId, onMachineSourceUpdate, onMachineSourceInsert } = this.props;

    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id'
      }, {
        title: '名称',
        dataIndex: 'name',
        key: 'name'
      }, {
        title: 'Master Url',
        dataIndex: 'masterUrls',
        key: 'masterUrls'
      }, {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render(status){
          return {
            ACTIVE: <span>正常</span>,
            LOCK: <span>已锁定</span>
          }[status]
        }
      }, {
        title: '归属',
        key: 'belong',
        render(t, source) {
          return !!source.companyId ? `私有：${source.companyName}` : '公共';
        }
      }, {
        title: '操作',
        key: 'operator',
        render: (t, source) => {
          return (!!companyId && !source.companyId) ? null : (
            <span className='btn-line'>
              <Button onClick={() => this.refs.editMachineSourceModal.show(source)}><Icon type='edit'/>修改</Button>
              {{
                ACTIVE: <Popconfirm title="确定要锁定这个机器来源吗？" onConfirm={::this.lockSource(source)}>
                  <Button type='primary'><Icon type='lock'/>锁定</Button>
                </Popconfirm>,
                LOCK: <Popconfirm title="确定要解锁这个机器来源吗？" onConfirm={::this.unlockSource(source)}>
                  <Button type='primary'><Icon type='unlock'/>解锁</Button>
                </Popconfirm>
              }[source.status]}
            </span>
          );
        }
      }
    ];

    return (
      <Panel className='machine-source-manage' title={`机器来源管理 (${sources.length})`}>
        <Button type='primary' style={{ marginBottom: '10px' }}
          onClick={() => this.refs.editMachineSourceModal.show()}
        >
          <Icon type='plus-circle-o'/> 新增机器来源
        </Button>
        <Table dataSource={sources} columns={columns} loading={isFetching} pagination={false} rowKey={it => it.id}/>
        <EditMachineSourceModal ref='editMachineSourceModal'
          onMachineSourceUpdate={onMachineSourceUpdate}
          onMachineSourceInsert={onMachineSourceInsert}
          companyId={companyId}
        />
      </Panel>
    );
  }
}

export default MachineSourceManage;
